from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from main.models import User, Room
from main.serializer import UserModelSerializers, RoomModelSerializers
from uuid import uuid4
from main.jwt import jwt_get_user
from mqtt.mqtt_publish import mqtt_publish


class UserInfoViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserModelSerializers

    def list(self, request):
        # 获取模型数据
        user = jwt_get_user(request)
        s = UserModelSerializers(instance=user)
        return Response({
            'code': 200,
            'msg': 'success',
            'user_info': s.data
        })

    def logout(self, request):
        user = jwt_get_user(request)
        user.user_secret = uuid4()
        user.user_jwt = ''
        user.save()
        s = UserModelSerializers(instance=user)
        return Response({
            'code': 200,
            'msg': 'success',
            'user_info': s.data
        })


class RoomViewSet(ModelViewSet):
    def changeRoomStatus(self, request):
        user = jwt_get_user(request)
        req = request.query_params
        if int(req['door_status']) == user.room.door_status.type:
            if not user.room.door_status.type:
                err_res = '已关门，请勿重复关门'
            elif user.room.door_status.type:
                err_res = '已开门，请勿重复开门'
            return Response({
                'code': 400,
                'msg': err_res
            })
        else:
            try:
                mqtt_publish(user.username, user.password, user.room.number, int(req['door_status']))
            except:
                err_res = 'mqtt发送消息失败，开门失败'
                return Response({
                    'code': 500,
                    'msg': err_res
                })
            else:
                user.room.door_status_id = int(req['door_status']) + 1
                user.room.save()
                s = UserModelSerializers(instance=user)
                return Response({
                    'code': 200,
                    'msg': 'success',
                    'data': s.data
                })

